import { Injectable, Inject, HttpException, HttpStatus } from '@nestjs/common';
import { User } from 'src/entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import {
  Response,
  ResponseParam,
  UserError,
  CurrentError,
} from '../../common/enums/response';
import { ApiErrorCode } from '../../common/enums/api-error-code.enum';
import { Auth } from '../../auth/auth';
import { Login } from './admin.dto';

@Injectable()
export class AdminService {
  constructor() {}
  @InjectRepository(User) private readonly user: Repository<User>;

  public async login(param: Login) {
    try {
      const adminInfo = await this.user.findOneBy({
        phone: param.account,
        password: param.password,
      });
      if (adminInfo && adminInfo.role == 'admin') {
        let auth = new Auth();
        const role: string = adminInfo.role;
        const token = await auth.createToken(adminInfo.id, role);
        let data = new Object();
        data['info'] = adminInfo;
        data['token'] = token;
        let responseParam: ResponseParam = {
          message: ApiErrorCode.LCAK_LOGIN_SUCCESS,
          data,
        };
        return Response(responseParam);
      } else {
        return UserError.USER_USERINFO_ERROR;
      }
    } catch (error) {
      console.log(error);
      throw new HttpException(
        ApiErrorCode.LCAK_LOGIN_FAIL,
        HttpStatus.FORBIDDEN,
      );
    }
  }

  public async userLogin(param: Login) {
    try {
      const adminInfo = await this.user.findOneBy({
        phone: param.account,
        password: param.password,
      });

      if (adminInfo && adminInfo.role == 'general') {
        let auth = new Auth();
        const role: string = adminInfo.role;
        const token = await auth.createToken(adminInfo.id, role);
        let data = new Object();
        data['info'] = adminInfo;
        data['token'] = token;
        let responseParam: ResponseParam = {
          message: ApiErrorCode.LCAK_LOGIN_SUCCESS,
          data,
        };
        return Response(responseParam);
      } else {
        return UserError.USER_USERINFO_ERROR;
      }
    } catch (error) {
      console.log(error);
      throw new HttpException(
        ApiErrorCode.LCAK_LOGIN_FAIL,
        HttpStatus.FORBIDDEN,
      );
    }
  }
}
